package edu.nju.desserthouse.dao.impl;

import java.util.ArrayList;
import java.util.List;

import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import nju.edu.desserthouse.model.Clerk;
import edu.nju.desserthouse.dao.ClerkDao;

/**
 * Session Bean implementation class ClerkDao
 */
@Stateless
public class ClerkDaoBean implements ClerkDao{

	private static final long serialVersionUID = 1L;
	
	@PersistenceContext(unitName = "desserthouseJPA")
	protected EntityManager em;
	
	public ClerkDaoBean(){
		
	}

	@Override
	public boolean save(Clerk clerk) {
		try{
			em.persist(clerk);
		}catch(Exception e){
			e.printStackTrace();
			return false;
		}
		return true;
	}

	@Override
	public Clerk find(String column, String value) {
		Clerk clerk = null;
		try{
			Query query = em.createQuery("from Clerk c where c." + column + "=" + value);
			clerk = (Clerk)query.getSingleResult();
			em.clear();
			return clerk;
		}catch(Exception e){
			e.printStackTrace();
			return null;
		}
	}

	@Override
	public boolean updateByClerkId(Clerk clerk) {
		try{
			em.merge(clerk);
		}catch(Exception e){
			e.printStackTrace();
			return false;
		}
		return true;
	}

	@Override
	public Clerk find(String col1, String val1, String col2, String val2, int privilege){
		Clerk clerk = null;
		try{
			Query query = em.createQuery("from Clerk c where c." + col1 + "= '" + val1 + "' and c." + col2 + "= '" + val2 + "'");
			clerk = (Clerk) query.getSingleResult();
			em.clear();
			if(clerk.getPrivilege() == privilege){
				return clerk;
			}else{
				return null;
			}
		}catch(Exception e){
			e.printStackTrace();
			return null;
		}
	}
	
	@Override
	public ArrayList<Clerk> getClerkList() {
		try{
			Query query = em.createQuery("from Clerk c where c.id > 0");
			@SuppressWarnings("unchecked")
			List<Clerk> clerks = query.getResultList();
			if(clerks != null){
				ArrayList<Clerk> clerkList = new ArrayList<Clerk>(clerks);
				em.clear();
				return clerkList;
			}else{
				System.out.println("NULL RESULT!!!");
				em.clear();
				return null;
			}
		}catch(Exception e){
			e.printStackTrace();
			return null;
		}
	}
	
	@Override
	public boolean delete(String id) {
		Clerk clerk = null;
		try{
			Query query = em.createQuery("from Clerk c where c.id = " + id);
			clerk = (Clerk) query.getSingleResult();
			if(clerk != null){
				em.remove(clerk);
				em.close();
				return true;
			}else{
				System.out.println("NULL!!!");
				em.close();
				return false;
			}
		}catch(Exception e){
			e.printStackTrace();
			return false;
		}
	}
}
